/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2025 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "MotionController_10.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
uint8_t rx_buffer[100];             // 接收缓冲区
uint8_t rx_len = 0;                 // 接收长度
uint8_t rx_char;                    // 单次接收字符
volatile uint8_t recv_end_flag = 0; // 接收完成标志

MotionController motionController; // 创建全局运动控制器实例
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
#ifdef __cplusplus
extern "C"
{
#endif
  // 设置RGB颜色（共阳极）
  void RGB_SetColor(uint8_t r, uint8_t g, uint8_t b)
  {
    // 共阳极RGB：低电平点亮，高电平关闭
    HAL_GPIO_WritePin(R_GPIO_Port, R_Pin, (GPIO_PinState)(r > 128));
    HAL_GPIO_WritePin(G_GPIO_Port, G_Pin, (GPIO_PinState)(g > 128));
    HAL_GPIO_WritePin(B_GPIO_Port, B_Pin, (GPIO_PinState)(b > 128));
  }

  // RGB_SetColor(0, 255, 255);   // 红色
  // RGB_SetColor(255, 0, 255);   // 绿色
  // RGB_SetColor(255, 255, 0);   // 蓝色
  // RGB_SetColor(0, 0, 255);     // 黄色
  // RGB_SetColor(0, 255, 0);     // 紫色
  // RGB_SetColor(255, 0, 0);     // 青色
  // RGB_SetColor(0, 0, 0);       // 白色
  // RGB_SetColor(255, 255, 255); // 黑色（关闭）

  // 初始化DWT
  void DWT_Init(void)
  {
    CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
    DWT->CYCCNT = 0;
    DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
  }

  // us延时函数
  void delay_us(uint32_t us)
  {
    uint32_t start = DWT->CYCCNT;
    uint32_t cycles = us * (SystemCoreClock / 1000000);
    while ((DWT->CYCCNT - start) < cycles)
      ;
  }

  /* 重定向printf */
  int _write(int file, char *ptr, int len)
  {
    HAL_UART_Transmit(&huart1, (uint8_t *)ptr, len, HAL_MAX_DELAY);
    return len;
  }

  void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
  {
    if (huart->Instance == USART1)
    {
      if (rx_char == '\r' || rx_char == '\n') // 判断接收到换行符
      {
        if (rx_len > 0) // 只有接收到内容才处理
        {
          rx_buffer[rx_len] = '\0'; // 字符串结束符
          // printf("rx_buffer: %s",rx_buffer);
          recv_end_flag = 1; // 置位接收完成标志
        }
        rx_len = 0; // 清零长度, 准备下一次接收
      }
      else
      {
        if (rx_len < sizeof(rx_buffer) - 1) // 预留一位给 '\0'
        {
          rx_buffer[rx_len++] = rx_char; // 字符存入缓冲区
        }
      }
      HAL_UART_Receive_IT(&huart1, &rx_char, 1); // 再次使能接收中断
    }
  }

#ifdef __cplusplus
}
#endif
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  MX_TIM4_Init();
  /* USER CODE BEGIN 2 */
  HAL_UART_Receive_IT(&huart1, &rx_char, 1); // 启动第一次UART接收中断
  RGB_SetColor(255, 255, 255);               // 黑色（关闭）

  // 1. 初始化微秒计时（基于TIM2）
  DWT_Init();
  micros_init();
  // printf("Stepper motor timer initialized\r\n");

  // 2. 初始化74HC595移位寄存器
  hc595_init();
  // printf("74HC595 shift register initialized\r\n");

  // 3. 初始化OLED
  OLED_Init();  // OLED初始化
  OLED_Clear(); // 清屏
  OLED_ShowString(6, 3, "OLED Starting      ...  ");

  // 4. 初始化电机
  motionController.init();

  /* *****************************浮点测试代码****************************** */
  // 测试1：基础串口输出
  HAL_UART_Transmit(&huart1, (uint8_t *)"--- UART Test Start ---\r\n", 24, HAL_MAX_DELAY);

  // 测试2：直接打印浮点数
  float testFloat = 123.45f;
  char floatStr[32];

  sprintf(floatStr, "%6.2f", testFloat); // 替换 dtostrf // 打印 floatStr 内容到调试控制台（PlatformIO Monitor）

  printf("floatStr = [%s]\r\n", floatStr);
  printf("Test float via printf: %f\r\n", testFloat);

  HAL_UART_Transmit(&huart1, (uint8_t *)"DTOSTRF: ", 9, HAL_MAX_DELAY);
  HAL_UART_Transmit(&huart1, (uint8_t *)floatStr, strlen(floatStr), HAL_MAX_DELAY);
  HAL_UART_Transmit(&huart1, (uint8_t *)"\r\n", 2, HAL_MAX_DELAY);

  // 测试3：printf 重定向测试（需已实现 _write）
  printf("PRINTF: %.2f\r\n", testFloat); // 验证是否修复

  // 打印 floatStr 内容到调试控制台（PlatformIO Monitor）
  printf("floatStr = [%s]\r\n", floatStr);
  /* *********************************************************************** */

  for (int i = 1; i < 5; i++) // 闪黄灯表示初始化完成
  {
    RGB_SetColor(0, 0, 155); // 黄色
    HAL_Delay(125);
    RGB_SetColor(255, 255, 255); // 黑色（关闭）
    HAL_Delay(125);
  }
  OLED_Clear();
  // fill_picture(0xFF); // 全屏点亮

  // // 初始化电机状态：禁用、默认方向、低电平步进信号
  // motor_set_signal(MOTOR_A, MOTOR_EN, 1);   // 禁用A轴（EN=1为禁用）
  // motor_set_signal(MOTOR_A, MOTOR_DIR, 0);  // 设置方向为正向（DIR=0）
  // motor_set_signal(MOTOR_A, MOTOR_STEP, 0); // 步进信号初始为低
  // motor_update_outputs();                   // 同步输出到74HC595

  // // 启用电机
  // motor_set_signal(MOTOR_A, MOTOR_EN, 0); // 使能A轴（EN=0为使能）
  // motor_update_outputs();
  // HAL_Delay(100); // 等待电机启动稳定
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    // // 生成一个步进脉冲（高电平）
    // motor_set_signal(MOTOR_A, MOTOR_STEP, 1);
    // motor_update_outputs(); // 同步高电平信号
    // delay_us(5);          // 脉冲宽度100us（可调整）

    // // 步进脉冲结束（低电平）
    // motor_set_signal(MOTOR_A, MOTOR_STEP, 0);
    // motor_update_outputs(); // 同步低电平信号
    // delay_us(705);         // 脉冲间隔1ms（控制速度，值越小速度越快）

    // 脉冲周期us->10圈时间 250->15s 150->13s 55->9s
    // 脉冲周期us->10圈时间 350->18s 450->23s 550->25s 700->31s

    motionController.update(); // 更新运动控制器状态
  }
  /* USER CODE END 3 */
}

void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
   */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
   * in the RCC_OscInitTypeDef structure.
   */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV1;
  RCC_OscInitStruct.PLL.PLLN = 18;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV4;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
   */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef USE_FULL_ASSERT
/**
 * @brief  Reports the name of the source file and the source line number
 *         where the assert_param error has occurred.
 * @param  file: pointer to the source file name
 * @param  line: assert_param error line source number
 * @retval None
 */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
